package com.naiterui.ehp.bs.doctor.service.impl;

import com.naiterui.ehp.bs.doctor.dao.IBeforePasswordDao;
import com.naiterui.ehp.bs.doctor.domain.DrBeforePassword;
import com.naiterui.ehp.bs.doctor.service.IBeforePasswordService;
import com.naiterui.ehp.bs.doctor.utils.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author guoyongxiang
 * @date 2019-06-22 15:06
 * @since 1.0.0
 */
@Service
public class AdBeforePasswordServiceImpl implements IBeforePasswordService {

    @Autowired
    private IBeforePasswordDao beforePasswordDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveBeforePassword(Long userId, String password, String salt) {
        DrBeforePassword beforePassword = new DrBeforePassword();
        beforePassword.setUserId(userId);
        String encodePassword = PasswordUtil.encode(getSaltPassword(password, salt));
        beforePassword.setEncryptPassword(encodePassword);
        beforePassword.setCreatedAt(new Date());
        beforePasswordDao.save(beforePassword);
    }

    @Override
    public boolean verifyRepetBeforePassword(Long userId, String password, String salt, int times) {
        // 历史数+2 删除多余记录
        List<DrBeforePassword> beforePasswordList = beforePasswordDao.findLastBeforePasswordLimit(userId, times + 2);
        for (int i = 0; i < beforePasswordList.size(); i++) {
            DrBeforePassword beforePassword = beforePasswordList.get(i);
            if (i < times) {
                String saltPassword = getSaltPassword(password, salt);
                boolean matches = PasswordUtil.matches(saltPassword, beforePassword.getEncryptPassword());
                if (matches) {
                    return true;
                }
            } else {
                beforePasswordDao.removeById(beforePassword.getId());
            }
        }
        return false;
    }

    private String getSaltPassword(String password, String salt) {
        return password + salt;
    }
}
